﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Routine.API.Models;
using Routine.API.Services;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Routine.API.Controllers
{
    /*[ApiController] 属性并不是强制要求的，但是它会使开发体验更好
     * 它会启用以下行为：
     * 1.要求使用属性路由（Attribute Routing）
     * 2.自动HTTP 400响应
     * 3.推断参数的绑定源
     * 4.Multipart/form-data请求推断
     * 5.错误状态代码的问题详细信息
     */
    [Route("api/[controller]")]  //建议[Route("api/companies")]
    [ApiController]
    public class CompaniesController : ControllerBase
    {
        private readonly ICompanyRepository _companyRepository;
        private readonly IMapper _mapper;

        public CompaniesController(ICompanyRepository companyRepository, IMapper mapper)
        {
            _companyRepository = companyRepository ??
                                 throw new ArgumentNullException(nameof(companyRepository));
            _mapper = mapper ??
                                 throw new ArgumentNullException(nameof(mapper));
        }

        [HttpGet]
        [HttpHead]
        public async Task<ActionResult<IEnumerable<CompanyDto>>> GetCompanies()
        {
            var companies = await _companyRepository.GetCompaniesAsync();

            var companyDtos = _mapper.Map<IEnumerable<CompanyDto>>(companies);
            return Ok(companyDtos);
        }

        [HttpGet("{companyId}")]
        public async Task<ActionResult> GetCompany(Guid companyId)
        {
            var company = await _companyRepository.GetCompanyAsync(companyId);

            if (company == null)
                return NotFound();

            return Ok(_mapper.Map<CompanyDto>(company));
        }

        [HttpPost]
        public async Task<ActionResult<CompanyDto>> CreateCompany()
        {

        }
    }
}
